// const { Controller } = require('egg');
const BaseController = require('./base');
class ArticleController extends BaseController {
  // 获取所有文章
  async index() {
    const { service } = this;
    const { page, pageSize, cateId, state } = this.ctx.query;
    console.log(page);
    const { count } = await this.ctx.model.Article.findAndCountAll();
    if (page && pageSize) {
      const getArtileList = await service.article.getArticle(page, pageSize);
      if (getArtileList) {
        this.ctx.body = {
          code: 200,
          msg: '文章获取成功',
          data: getArtileList,
          pageInfo: {
            page, // 查询起始位置
            pageSize,
            cateId, // 分类id
            state, // 发布状态
          },
          totalArticle: count,
        };
      } else {
        this.error('页码或者限制不存在', 400);
      }
    } else {
      // 不传页码的时候使用的查询
      const getArtileList2 = await service.article.getArticle();
      if (getArtileList2) {
        this.ctx.body = {
          code: 200,
          msg: '文章获取成功',
          data: getArtileList2,
          totalArticle: count,
        };
      } else {
        this.error('文章列表获取失败');
      }
    }


  }
  // 根据文章id获取文章
  async show() {
    const { service, ctx } = this;
    const id = ctx.params.id;
    const getArticleIdList = await service.article.getArticleById(id);
    if (getArticleIdList) {
      this.success(getArticleIdList, '文章获取成功');
    } else {
      this.error('文章获取失败', 400);
    }
  }
  // 新增一篇文章
  // 上传七牛云

  async create() {
    const { ctx, service } = this;
    const file = ctx.request.files[0];

    const data = ctx.request.body;
    const result = await service.uploadQiniu.upload(file);

    data.image_url = `http://reservation.mamenglei.top/${result.key}`;

    // console.log(title, state);
    // const data = ctx.request.body;
    // // console.log(data);
    const addArticle = await service.article.addArticle(data);
    if (addArticle) {
      this.success(addArticle, '新增文章成功');
    } else {
      this.error('文章新增失败', 400);
    }
  }
  // 删除一篇文章
  async destroy() {
    const { ctx, service } = this;
    const id = ctx.params.id;
    const delArticle = await service.article.delArticle(id);
    if (delArticle) {
      this.success(delArticle, '文章删除成功');
    } else {
      this.error('文章删除失败', 500);
    }
  }
  // 根据文章id更新一篇文章
  async update() {
    const { ctx, service } = this;
    const id = ctx.params.id;
    const data = ctx.request.body;
    const updateArticle = await service.article.updateArticle(id, data);
    if (updateArticle) {
      this.success(updateArticle, '文章更新成功');
    } else {
      this.error('文章更新失败', 500);
    }
  }
}


module.exports = ArticleController;
